package cn.sinata.wanglin.mine.activity;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.design.widget.TextInputLayout;
import android.text.Editable;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.google.gson.JsonObject;
import com.xilada.xldutils.activitys.TitleActivity;
import com.xilada.xldutils.utils.SharedPreferencesUtils;
import com.xilada.xldutils.utils.StringUtils;

import butterknife.BindView;
import butterknife.OnClick;
import butterknife.OnTextChanged;
import cn.sinata.wanglin.R;
import cn.sinata.wanglin.commonutils.Constant;
import cn.sinata.wanglin.model.BindPhoneInfo;
import cn.sinata.wanglin.net.HttpManager;
import cn.sinata.wanglin.net.model.ResultData;
import cn.sinata.wanglin.net.model.util.ResultDataSubscriber;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action0;
import rx.schedulers.Schedulers;

/**
 * 第三方登录绑定手机；
 */
public class BindPhoneForAuthActivity extends TitleActivity {

    @BindView(R.id.et_new_phone)
    EditText et_new_phone;
    @BindView(R.id.et_code)
    EditText et_code;
    @BindView(R.id.tv_getCode)
    TextView tv_getCode;
    private boolean isTimerStart = false;
    @Override
    protected int setContentId() {
        return R.layout.activity_bind_phone_for_auth;
    }
    @OnTextChanged(value = R.id.et_new_phone,callback = OnTextChanged.Callback.AFTER_TEXT_CHANGED)
    void afterNewPhoneTextChanged(Editable s){
        if (!TextUtils.isEmpty(s) && s.length() == 11 && StringUtils.isPhoneNumberValid(s.toString()) ){
            if (!isTimerStart) {
                tv_getCode.setEnabled(true);
            }
        }else {
            tv_getCode.setEnabled(false);
        }
    }
    @Override
    protected void initView() {
        super.initView();
        setTitle("绑定手机");
        Bundle mBundle=getIntent().getExtras();
        if(mBundle!=null){
            String fromWhere= mBundle.getString("fromWhere");
            if("login".equals(fromWhere)){
                addRightButton("跳过", new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        setResult(RESULT_OK);
                        finish();
                    }
                });

            }
        }
    }
    @OnClick({R.id.tv_getCode,R.id.tv_action})
    void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_getCode:
                //描述:
                sendSMSCode();
                break;
            case R.id.tv_action:
                //描述:
                String newPhone= et_new_phone.getText().toString().trim();
                String code = et_code.getText().toString().trim();

                if (TextUtils.isEmpty(newPhone) || newPhone.length() != 11 ||! StringUtils.isPhoneNumberValid(newPhone.toString())){
                    showToast("请填写正确的手机号!");
                    return;
                }
                if (TextUtils.isEmpty(code)||code.length()!=6){
                    showToast("请填写正确的验证码!");
                    return;
                }
                showDialog();
                doBindPhone(newPhone,code);
                break;
        }
    }

    private void doBindPhone( final String newPhone, String code) {
        String userid= SharedPreferencesUtils.getString(Constant.SP_USERID);
        HttpManager.bindPhone(userid,"",newPhone,code).subscribe(new ResultDataSubscriber<BindPhoneInfo>(this) {
            @Override
            public void onSuccess(String msg, BindPhoneInfo bindPhoneInfo) {
                showToast(msg);
                SharedPreferencesUtils.save(Constant.SP_PHONE,newPhone);
                setResult(RESULT_OK);
                finish();
            }
        });
    }

    /**
     * 获取短信验证码
     */
    private void sendSMSCode(){
        String phone = et_new_phone.getText().toString().trim();
        Observable<ResultData<JsonObject>> observable = HttpManager.sendCodeSms(phone,"C");
        observable.subscribeOn(Schedulers.io())
                .doOnSubscribe(new Action0() {
                    @Override
                    public void call() {
                        showDialog();
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ResultDataSubscriber<JsonObject>(this) {
                    @Override
                    public void onSuccess(String msg, JsonObject jsonObject) {
                        showToast(msg);
                        timer.start();
                        isTimerStart = true;
                        tv_getCode.setEnabled(false);
                    }
                });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(timer!=null) {
            timer.cancel();
        }
    }
    private CountDownTimer timer = new CountDownTimer(60*1000,1000) {
        @Override
        public void onTick(long millisUntilFinished) {

            if (isDestroy){
                return;
            }
            tv_getCode.setText(String.format("%s",(millisUntilFinished/1000)));
        }

        @Override
        public void onFinish() {
            tv_getCode.setText("获取验证码");
            isTimerStart = false;
            tv_getCode.setEnabled(true);
        }
    };

    @Override
    public void onBackPressed() {
        setResult(RESULT_OK);
        finish();
    }
}
